#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
class Tickets
{
    private:
        int tickets;           //票数
        pthread_mutex_t mutex; //定义一把锁
    public:
    Tickets(int ticket):tickets(ticket)
    {
        pthread_mutex_init(&mutex,nullptr); //初始化锁
    }
    bool GetTickets()
    {
        bool flag = true; //表示有票
        pthread_mutex_lock(&mutex);    //加锁
        if(tickets > 0) 
        {
           
            //抢票
            usleep(1000); //休眠1毫秒s
            tickets--;
            printf("我是线程[%lu],我抢得票是第%d\n",pthread_self(),tickets);
        }
        else
        {
            //没票了
            printf("票被抢完了，亲！！！！\n");
            flag = false;//无票
        }
        pthread_mutex_unlock(&mutex);

        return flag;
    }
    ~Tickets()
    {
        pthread_mutex_destroy(&mutex);
    }
};
//5个线程抢票
void* ThreadRun(void* argc)
{
    Tickets* t = (Tickets*) argc;
    while(true)
    {
        if(!t->GetTickets())
        {
            break;
        }
        else
        {
            continue;
        }
    }
    return (void*)0;
}

int main()
{
    Tickets* t = new Tickets(1000); //创建对象1000张票
    
    pthread_t tid[5];               //创建五个线程进行抢票
    for(int i = 0;i < 5;i++){
        pthread_create(tid+i,NULL,ThreadRun,(void*)t); //pthread_create 在函数调用中启动一个新线程
                                                       //新线程从threadrun开始执行
    }

    for(int i = 0; i< 5;i++){
        pthread_join(tid[i],NULL);
    }
    return 0;
}
